# Contributor: Oleg A. Khlybov <fougas@mail.ru>

_realname=msmpi
pkgbase=mingw-w64-${_realname}
pkgname="${MINGW_PACKAGE_PREFIX}-${_realname}"
pkgver=10.1.1
pkgrel=2
pkgdesc="Microsoft MPI SDK (mingw-w64)"
arch=('any')
url="https://docs.microsoft.com/en-us/message-passing-interface/microsoft-mpi"
license=('MIT')
makedepends=("${MINGW_PACKAGE_PREFIX}-binutils")
depends=("${MINGW_PACKAGE_PREFIX}-gcc" "${MINGW_PACKAGE_PREFIX}-gcc-fortran")
options=('strip')
source=(
  'mpi.c'
  'mpi.h'
  'mpif.h'
  'mpi.f90'
  'mpifptr.h.x86_64'
  'mpifptr.h.i686'
  'msmpi.def.x86_64'
  'msmpi.def.i686'
)
sha256sums=(
  'b77161211b70dbdd866e3df710c4a0e54d74b1421dade0a2f5c716fb5f2b82d9'
  'baee3f18f38650e7182956baa0d3d8f8e5c26d8603ccee4871a4dbd160c13660'
  'f3384eeb848164e518edfd2b2b9ff1d0f33e267efd5811d5a7c5f79ef7a0a81e'
  '38e7be31ad555570f6122058317c08504472b8cfd0a198cdad827519b941ba2c'
  '031f910c6ce9a0f7bf66365dd4271fa36530f32c5d22755b10ef2d89dc605e1f'
  '4ff6e817fe7517f04f0ca04a038e4c136264384d36f520b79995604e3986fce4'
  'fd18184993872fc4eaea825e85f974dca4b020598d838c424c6c112c2328cf2a'
  '7b8ed9d3e257e439678cc648164164d6817f7fde68530055b392f67d97bf8ec8'
)

build() {
  [[ -d ${srcdir}/build-${MINGW_CHOST} ]] && rm -rf ${srcdir}/build-${MINGW_CHOST}
  mkdir -p ${srcdir}/build-${CARCH} && cd ${srcdir}/build-${CARCH}
  mkdir -p bin include lib
  # Import library
  ${MINGW_PREFIX}/bin/dlltool -k -d "$srcdir/msmpi.def.${CARCH}" -l lib/libmsmpi.a
  # Headers
  cp $srcdir/{mpi.h,mpif.h,mpi.f90} include
  cp $srcdir/mpifptr.h.${CARCH} include/mpifptr.h
  # Compiler wrappers
  mpic="$srcdir/mpi.c"
  cflags="-s -O2 -DNDEBUG"
  gcc ${cflags} -o bin/mpicc.exe -DCC "${mpic}"
  gcc ${cflags} -o bin/mpicxx.exe -DCXX "${mpic}"
  cp bin/mpicxx.exe bin/mpic++.exe
  gcc ${cflags} -o bin/mpifort.exe -DFC "${mpic}"
  cp bin/mpifort.exe bin/mpif77.exe
  cp bin/mpifort.exe bin/mpif90.exe
}

package() {
  cd "${srcdir}/build-${CARCH}"
  mkdir -p "${pkgdir}${MINGW_PREFIX}/lib/pkgconfig"
  cp -r * "${pkgdir}${MINGW_PREFIX}"
  echo "
    prefix=${MINGW_PREFIX}
    libdir=\${prefix}/lib
    includedir=\${prefix}/include
    Name: ${_realname}
    URL: ${url}
    Version: ${pkgver}
    Description: ${pkgdesc}
    Cflags: -I\${includedir}
    Libs: -L\${libdir} -l${_realname}
  " | sed '/^\s*$/d;s/^\s*//' > "${pkgdir}${MINGW_PREFIX}/lib/pkgconfig/${_realname}.pc"
}
